package com.lpf.mybatis.executor.impl;

import com.lpf.mybatis.config.Configuration;
import com.lpf.mybatis.config.MapperRegistry;
import com.lpf.mybatis.executor.Executor;
import com.lpf.mybatis.statement.StatementHandler;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("all")
public class CachingExecutor implements Executor {

    private Configuration configuration;
    private SimpleExecutor delegate;

    private Map<String, Object> localCache = new HashMap();

    public CachingExecutor(SimpleExecutor delegate) {
        this.delegate = delegate;
    }

    public CachingExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 功能描述：执行查询。先从缓存中获取，缓存没有去查询数据库。
     *
     * @param mapperData 根据 statementId 在 MapperRegistry 中找到的配置信息（sql、实体类型等）
     * @param parameter  设置到 sql 语句中的数据
     * @return E
     */
    public <E> E query(MapperRegistry.MapperData mapperData, Object parameter) throws Exception {

        //初始化StatementHandler --> ParameterHandler --> ResultSetHandler
        StatementHandler handler = new StatementHandler(configuration);

        // 从缓存中获取（key为sql语句）
        Object result = localCache.get(mapperData.getSql());
        if (result != null) {
            System.out.println("缓存命中");
            return (E) result;
        }

        result = (E) delegate.query(mapperData, parameter);

        localCache.put(mapperData.getSql(), result);

        return (E) result;
    }
}